package com.keller.guli.service.edu.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.keller.guli.service.edu.entity.Subject;
import com.keller.guli.service.edu.entity.excel.ExcelSubjectData;
import com.keller.guli.service.edu.mapper.SubjectMapper;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

@Slf4j
@AllArgsConstructor //全参
@NoArgsConstructor //无参
public class ExcelSubjectDataListener extends AnalysisEventListener<ExcelSubjectData> {

    @Autowired
    private SubjectMapper subjectMapper;

    @Override
    public void invoke(ExcelSubjectData data, AnalysisContext analysisContext) {
        //读取数据
        String levelOneTitle = data.getLevelOneTitle();
        String levelTwoTitle = data.getLevelTwoTitle();

        //判断一级分类是否重复
        Subject levelOneSubject = getSubjectByTitle(levelOneTitle, "0");
        String parentId = null;
        if(levelOneSubject == null){
            //将一级分类存入数据库
            Subject subject = new Subject();
            subject.setParentId("0");
            subject.setTitle(levelOneTitle);//一级分类名称
            subjectMapper.insert(subject);
            parentId = subject.getId();
        }else {
            parentId = levelOneSubject.getId();
        }

        //判断二级分类是否重复
        Subject levelTwoSubject = getSubjectByTitle(levelOneTitle, parentId);
        if(levelTwoSubject == null){
            //将二级分类存入数据库
            Subject subject = new Subject();
            subject.setTitle(levelTwoTitle);
            subject.setParentId(parentId);
            subjectMapper.insert(subject);//添加
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }

    //判断名称和parentid判断分类是否存在
    private Subject getSubjectByTitle(String title, String parentId){
        QueryWrapper<Subject> wrapper = new QueryWrapper<>();
        wrapper.eq("title", title);
        wrapper.eq("parent_id", parentId);
        return subjectMapper.selectOne(wrapper);
    }
}
